package com.cxb.java;

/**
 * @Classname ReOrderTest
 * @Date 2023/4/12 21:35
 * @Created by Administrator
 * @Description TODO
 */
public class ReOrderTest {
    private static int x = 0, y = 0;
    private static int a = 0, b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        while (true) {
            i++;
            x = 0;
            y = 0;
            a = 0;
            b = 0;
            /**
             * x,y: 00,01,10,11
             */
            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    shortWait(2000);
                    a = 1;
                    x = b;    //如果 x = b这句代码在a = 1的上面会出现(0,0)的情况
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y = a;
                }
            });

            t1.start();
            t2.start();
            t1.join();
            t2.join();

            System.out.println("第" + i + "次(" + x + "," + y + ")");
            if (x == 0 && y == 0) {
                break;
            }
        }
    }

    public static void shortWait(long interval) {
        long start = System.currentTimeMillis();
        long end;
        do {
            end = System.nanoTime();
        } while (start + interval >= end);
    }
}
